package com.cc.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cc.cmn.listener.DictlListener;
import com.cc.cmn.mapper.DictMapper;
import com.cc.cmn.service.DictService;
import com.cc.yygh.model.cmn.Dict;
import com.cc.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {//ServiceImpl已经注入了BaseMapper

    //根据id查询子数据
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")//springcache加redis,将查询的数据加入缓存
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);//查询parent_id=id
        List<Dict> dictlist = baseMapper.selectList(wrapper);
        for (Dict dict:dictlist){
            Long dictId = dict.getId();
            boolean ischild = this.isChildRen(dictId);
            dict.setHasChildren(ischild);
        }
        return dictlist;
    }

    //判断是否有子节点
    private boolean isChildRen(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);//查询parent_id=id
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }


    //导出字典
    @Override
    public void exportDictData(HttpServletResponse response) {

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName="dict";
        response.setHeader("Content-disposition","attachment:fileName="+fileName+".xlsx");
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
        for (Dict dict:dictList){
            DictEeVo dictEeVo=new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictVoList.add(dictEeVo);
        }
        //调用方法进行写
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictVoList);
        } catch (IOException e) {

        }
    }

    //导入字典
    @Override
    @CacheEvict(value = "dict",allEntries = true)//每次修改时候都清空缓存
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictlListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
